package org.example;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ValidateBarcodes {

    private static boolean isLetterDigital(String str) {
        String regex = "^[0-9A-Z]+$";
        return str.matches(regex);
    }

    private static boolean isDigital(String str) {
        String regex = "^[0-9]+$";
        return str.matches(regex);
    }

    private static boolean isNotNumberOrLarger100(String str) {
        if(!isDigital(str)) {
            return false;
        }
        int amount = Integer.parseInt(str);
        if(amount >= 100 || amount < 0) {
            return false;
        }
        return true;
    }

    public static boolean isProductExist(String barcode, JSONArray productListArray) {
        for(int i = 0; i < productListArray.size(); i++) {
            JSONObject productListJson = (JSONObject) productListArray.get(i);
            String barcodeValue = (String) productListJson.get("barcode");
            if(barcodeValue.equals(barcode)) {
                return true;
            }
        }
        return false;
    }

    public static JSONObject validate(String[] barcodesArray, JSONArray productList) {
        JSONObject jsonObject = new JSONObject();
        for(String barcode : barcodesArray){
            if(!barcode.contains("-")) {
                if(!isLetterDigital(barcode)) {
                    jsonObject.put("barcode", barcode);
                    jsonObject.put("error", "InvalidBarcode");
                    return jsonObject;
                }else if(!isProductExist(barcode, productList)){
                    jsonObject.put("barcode", barcode);
                    jsonObject.put("error", "product not found");
                    return jsonObject;
                }
            }else{
                String barcodeName = barcode.substring(0, barcode.indexOf("-"));
                String barcodeAmount = barcode.substring(barcodeName.length()+1);
                if(!isLetterDigital(barcodeName) || !isNotNumberOrLarger100(barcodeAmount)) {
                    jsonObject.put("barcode", barcode);
                    jsonObject.put("error", "InvalidBarcode");
                    return jsonObject;
                }else if(!isProductExist(barcodeName, productList)) {
                    System.out.println(barcodeName);
                    jsonObject.put("barcode", barcode);
                    jsonObject.put("error", "product not found");
                    return jsonObject;
                }
            }
        }
        jsonObject.put("error", "valid");
        return jsonObject;
    }
}
